//
//  SACommodityWarehousingCell.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/10/30.
//

#import "SACommodityWarehousingCell.h"
#import "SASalesOrderViewListModel.h"

@interface SACommodityWarehousingCell ()<UITextFieldDelegate>

@property (nonatomic, strong) UIButton *trashBtn;
@property (nonatomic, strong) UILabel *colourSizeLab;
@property (nonatomic, strong) UIButton *minusBtn;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UITextField *numTf;
@property (nonatomic, strong) UITextField *priceTf;
@property (nonatomic, strong) UILabel *countLab;
@property (nonatomic, strong) UIView *numLine;
@property (nonatomic, strong) UIView *priceLine;

@property (nonatomic, strong) UILabel *refundLabel;
@property (nonatomic, strong) UIImageView *hitImageView;
@property (nonatomic, strong) UILabel *hitLabel;
@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) NSString *cuttomStr;

@end

@implementation SACommodityWarehousingCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self initUI];
        self.overallSetting = [SAOverallSetting shareInstance];
    }
    return self;
}

-(void)setModel:(SASalesOrderToPendSkuList *)model {
    _model = model;
    _colourSizeLab.text = [NSString stringWithFormat:@"%@,%@",model.colourName,model.sizeName];
    _numTf.text = model.stock;
    
    NSString *price = [NSString stringWithFormat:@"%0.2f",[model.price doubleValue]/100.f];
    NSString *count = [NSString stringWithFormat:@"%0.2f",[model.price doubleValue]/100.f * [model.stock integerValue]];
    if ([self.model.price doubleValue] == 0) {
        count = @"0";
    }
    _priceTf.text = price;
    _countLab.text = count;
    _refundLabel.text = @"";
    
    if ( [model.stock integerValue] < 0) {
        self.numTf.textColor = kRedColor;
        self.priceTf.textColor = kRedColor;
        self.countLab.textColor = kRedColor;
    }else {
        self.numTf.textColor = kBlackColor;
        self.priceTf.textColor = kBlackColor;
        self.countLab.textColor = kBlackColor;
    }
    self.hitImageView.hidden = YES;
    self.refundLabel.text = @"";
    self.hitLabel.text = @"";
    
    _priceTf.userInteractionEnabled = YES;
    NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
    if ([productViewCostPrice isEqualToString:@"1"]) {
        _priceTf.text = @"******";
        _countLab.text = @"******";
        _priceTf.userInteractionEnabled = NO;
    }
}

-(void)refreshSaleModel:(SASalesOrderToPendSkuList *)model AndCuttomStr:(NSString *)cuttomStr Price:(NSString *)price {
    self.model = model;
    self.cuttomStr = cuttomStr;
    _colourSizeLab.text = [NSString stringWithFormat:@"%@,%@",model.colourName,model.sizeName];
    _numTf.text = model.stock;
    
    NSString *price2 = [NSString stringWithFormat:@"%0.2f",[price doubleValue]/100.f];
    NSString *count = [NSString stringWithFormat:@"%0.2f",[price2 doubleValue] * [model.stock integerValue]];
    if ([price2 doubleValue] == 0) {
        count = @"0";
    }
    _priceTf.text = price2;
    _countLab.text = count;
    _refundLabel.text = @"";
    
    [self showState];
}

//显示状态
-(void)showState {
    if ( [self.model.stock integerValue] < 0) {
        self.numTf.textColor = kRedColor;
        self.priceTf.textColor = kRedColor;
        self.countLab.textColor = kRedColor;
    }else {
        self.numTf.textColor = kBlackColor;
        self.priceTf.textColor = kBlackColor;
        self.countLab.textColor = kBlackColor;
    }
    
    if (self.cuttomStr.length >0) {
        if ([self.model.stock integerValue] >= 0) {
            if (self.overallSetting.isShowReplenishment == YES) {
                if ([self.model.replenishCount integerValue] >0) {
                    self.hitImageView.hidden = NO;
                    self.hitImageView.image = [UIImage imageNamed:@"sales_home_list_hit_1"];
                }else {
                    self.hitImageView.hidden = YES;
                }
            }else {
                self.hitImageView.hidden = YES;
            }
        }else {
            if (self.overallSetting.isShowReplenishmentReturn == YES) {
                if ([self.model.replenishCount integerValue] > 1) {
                    self.hitImageView.hidden = NO;
                    self.hitImageView.image = [UIImage imageNamed:@"sales_home_list_hit_2"];
                }else {
                    self.hitImageView.hidden = YES;
                }
            }
            if (self.overallSetting.timeLimitReturn >0) {
                if ([self getCurrentTimes:self.model.lastReplenishTime]-self.overallSetting.timeLimitReturn >0) {
                    self.hitImageView.hidden = NO;
                    self.hitLabel.hidden = NO;
                    self.hitImageView.image = [UIImage imageNamed:@"sales_home_list_hit_3"];
                    NSInteger day = [self getCurrentTimes:self.model.lastReplenishTime] - self.overallSetting.timeLimitReturn;
                    self.hitLabel.text = [NSString stringWithFormat:@"超%zd天",day];
                }
            }
        }
    }else {
        self.hitImageView.hidden = YES;
    }
    
    if (self.cuttomStr.length > 0) {
        if ([self.model.stock integerValue] + [self.model.backCount integerValue] < 0 &&[self.model.stock integerValue] < 0) {
            self.refundLabel.hidden = NO;
            NSInteger day = [self.model.stock integerValue]*(-1)-[self.model.backCount integerValue];
            self.refundLabel.text = [NSString stringWithFormat:@"(多退%zd)",day];
        }else {
            self.refundLabel.hidden = YES;
        }
    }else {
        self.refundLabel.hidden = YES;
    }
    
    if (self.hitImageView.isHidden == YES) {
        self.trashBtn.frame = SARectMake(26, 0, 20, 35);
    }else {
        self.trashBtn.frame = SARectMake(5, 0, 20, 35);
    }
    
    NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
    if ([productViewCostPrice isEqualToString:@"1"] && self.model != nil) {
        _countLab.text = @"******";
    }
}

-(void)clickedTrashBtn {
    !self.deleteBlock ?: self.deleteBlock();
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        return YES;
    }
    if (self.numTf == textField ) {
        if (textField.text.length > 5) {
            return NO;
        }
        
        if (self.isWarehousingStock == YES && [string isEqualToString:@"-"])
        {
            NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"-"];
            NSRange range2 = [textField.text rangeOfCharacterFromSet:tmpSet];
            if (range2.length > 0) {
                return NO;
            }else {
                if (range.location == 0) {
                    return YES;
                }else {
                    return NO;
                }
            }
        }
    }
    if (self.priceTf == textField && textField.text.length > 7) {
        return NO;
    }
    if ([string isEqualToString:@"-"] && textField.text.length > 0) {
        return NO;
    }
    // 如果第一位是.则前面加上0.
    if((textField.text.length == 0) && [string isEqualToString:@"."]) {
        textField.text = @"0";
    }
    if([textField.text containsString:@"."]) {
        if ([string isEqualToString:@"."]) {
            return NO;
        }
        NSRange ran = [textField.text rangeOfString:@"."];
        if(range.location > ran.location) {
            if([textField.text pathExtension].length > 1) {
                return NO;
            }
        }
    }
    return [self validateNumber:string];
}

- (void)textFieldEditChanged:(UITextField *)textField {
    if (self.numTf == textField) {
        if (textField.text.length == 0) {
            !self.inputBlock ?: self.inputBlock(@"");
        }else if ([textField.text isEqualToString:@"-"]) {
            !self.inputBlock ?: self.inputBlock(@"-");
        }else {
            NSInteger newNum = [textField.text integerValue];
            textField.text = [NSString stringWithFormat:@"%zd",newNum];
            !self.inputBlock ?: self.inputBlock(textField.text);
        }
        NSString *count = [NSString stringWithFormat:@"%0.2f",[self.model.price doubleValue]/100.f * [textField.text integerValue]];
        if ([self.model.price doubleValue] == 0) {
            count = @"0";
        }
        _countLab.text = count;
        
        NSString *productViewCostPrice = [NSString stringWithFormat:@"%@",[SAValueManger shareInStance].userInfo.menuList[1][@"perms"][@"productViewCostPrice"]];
        if ([productViewCostPrice isEqualToString:@"1"] && self.model != nil) {
            _countLab.text = @"******";
        }
    }
    
    if (self.priceTf == textField) {
        if (textField.text.length == 0) {
            self.model.noPirce = YES;
            !self.inputPriceBlock ?: self.inputPriceBlock(@"");
        }else {
            self.model.noPirce = NO;
            !self.inputPriceBlock ?: self.inputPriceBlock(textField.text);
        }
        NSString *count = [NSString stringWithFormat:@"%0.2f",[textField.text doubleValue] * [self.model.stock integerValue]];
        if ([self.model.price doubleValue] == 0) {
            count = @"0";
        }
        _countLab.text = count;
    }
    
    [self showState];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.numTf) {
        self.numLine.backgroundColor = kRedColor;
    }else if (textField == self.priceTf) {
        self.priceLine.backgroundColor = kRedColor;
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField == self.numTf) {
        self.numLine.backgroundColor = kBlackColor;
    }else if (textField == self.priceTf) {
        self.priceLine.backgroundColor = kBlackColor;
    }
    return YES;
}

#pragma mark - event
-(void)clickedMinusBtn {
    if (self.isWarehousingStock != YES) {
        if ([self.model.stock integerValue] == 0) {
            return;
        }
    }
    NSInteger num = [self.model.stock integerValue] - 1;
    self.numTf.text = [NSString stringWithFormat:@"%zd",num];
    NSString *count = [NSString stringWithFormat:@"%0.2f",[self.model.price doubleValue]/100.f * [self.numTf.text integerValue]];
    if ([self.model.price doubleValue] == 0) {
        count = @"0";
    }
    _countLab.text = count;
    !self.cutBlock ?: self.cutBlock();
    
    [self showState];
}

-(void)clickedAddBtn {
    NSInteger num = [self.model.stock integerValue] + 1;
    self.numTf.text = [NSString stringWithFormat:@"%zd",num];
    NSString *count = [NSString stringWithFormat:@"%0.2f",[self.model.price doubleValue]/100.f * [self.numTf.text integerValue]];
    if ([self.model.price doubleValue] == 0) {
        count = @"0";
    }
    _countLab.text = count;
    !self.addBlock ?: self.addBlock();
    
    [self showState];
}

#pragma mark - initUI
-(void)initUI {
    
    [self.contentView addSubview:self.colourSizeLab];
    [self.contentView addSubview:self.priceTf];
    [self.contentView addSubview:self.countLab];
    [self.contentView addSubview:self.numTf];
    [self.contentView addSubview:self.minusBtn];
    [self.contentView addSubview:self.addBtn];
    [self.contentView addSubview:self.numLine];
    [self.contentView addSubview:self.priceLine];
    [self.contentView addSubview:self.refundLabel];
    [self.contentView addSubview:self.hitImageView];
    [self.contentView addSubview:self.hitLabel];
//    [self.contentView addSubview:self.trashBtn];
}

#pragma mark - lazy
-(UIButton *)trashBtn {
    if (!_trashBtn) {
        _trashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_trashBtn setImage:[UIImage imageNamed:@"commodity_trash"] forState:UIControlStateNormal];
        _trashBtn.frame = SARectMake(26, 0, 20, 35);
        [_trashBtn addTarget:self action:@selector(clickedTrashBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _trashBtn;
}

-(UILabel *)colourSizeLab {
    if (!_colourSizeLab) {
        _colourSizeLab = [[UILabel alloc] initWithFrame:SARectMake(36, 0, 97, 35)];
        _colourSizeLab.textColor = kBlackColor;
        _colourSizeLab.textAlignment = NSTextAlignmentLeft;
        _colourSizeLab.font = kFont(14);
    }
    return _colourSizeLab;
}

-(UIButton *)minusBtn {
    if (!_minusBtn) {
        _minusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_minusBtn setImage:[UIImage imageNamed:@"commodity_minus"] forState:UIControlStateNormal];
        _minusBtn.frame = SARectMake(109, 0, 42, 35);
        _minusBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_minusBtn addTarget:self action:@selector(clickedMinusBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _minusBtn;
}

-(UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setImage:[UIImage imageNamed:@"commodity_add3"] forState:UIControlStateNormal];
        _addBtn.frame = SARectMake(211, 0, 42, 35);
        _addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

-(UITextField *)numTf {
    if (!_numTf) {
        _numTf = [[UITextField alloc] initWithFrame:SARectMake(151, 0, 60, 35)];
        _numTf.textColor = kBlackColor;
        _numTf.textAlignment = NSTextAlignmentCenter;
        _numTf.font = kFont(13);
        _numTf.delegate = self;
        _numTf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        [_numTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _numTf;
}

-(UITextField *)priceTf {
    if (!_priceTf) {
        _priceTf = [[UITextField alloc] initWithFrame:SARectMake(235, 0, 70, 35)];
        _priceTf.textColor = kBlackColor;
        _priceTf.textAlignment = NSTextAlignmentCenter;
        _priceTf.font = kFont(13);
        _priceTf.delegate = self;
        _priceTf.keyboardType = UIKeyboardTypeDecimalPad;
        [_priceTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _priceTf;
}

-(UILabel *)countLab {
    if (!_countLab) {
        _countLab = [[UILabel alloc] initWithFrame:SARectMake(305, 0, 70, 35)];
        _countLab.textColor = kBlackColor;
        _countLab.textAlignment = NSTextAlignmentCenter;
        _countLab.font = kFont(13);
    }
    return _countLab;
}

-(UILabel *)refundLabel {
    if (!_refundLabel) {
        _refundLabel = [[UILabel alloc] initWithFrame:SARectMake(151, 24, 60, 11)];
        _refundLabel.textColor = kBuleColor;
        _refundLabel.textAlignment = NSTextAlignmentCenter;
        _refundLabel.font = kFont(10);
    }
    return _refundLabel;
}

-(UIView *)numLine {
    if (!_numLine) {
        _numLine = [[UIView alloc] initWithFrame:SARectMake(151, 24, 60, 1)];
        _numLine.backgroundColor = kBlackColor;
    }
    return _numLine;
}

-(UIView *)priceLine {
    if (!_priceLine) {
        _priceLine = [[UIView alloc] initWithFrame:SARectMake(235, 24, 70, 1)];
        _priceLine.backgroundColor = kBlackColor;
    }
    return _priceLine;
}

-(UIImageView *)hitImageView {
    if (!_hitImageView) {
        _hitImageView = [[UIImageView alloc] initWithFrame:SARectMake(27, 4, 20, 20)];
    }
    return _hitImageView;
}

-(UILabel *)hitLabel {
    if (!_hitLabel) {
        _hitLabel = [[UILabel alloc] initWithFrame:SARectMake(2, 24, 70, 11)];
        _hitLabel.textColor = kYellowColor;
        _hitLabel.textAlignment = NSTextAlignmentCenter;
        _hitLabel.font = kFont(10);
    }
    return _hitLabel;
}

-(NSInteger)getCurrentTimes:(NSString *)timeStr{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    // NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    // NSLog(@"currentTimeString =  %@",currentTimeString);
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSDate* date = [formatter dateFromString:timeStr];
    NSInteger dateTimeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    //NSInteger count;
    NSInteger count = (timeSp-dateTimeSp)/86400;
    return count;
    
}

@end
